Ext.onReady(function(){
    Ext.QuickTips.init();
    Ext.BLANK_IMAGE_URL = '../../ext3.2/resources/images/default/s.gif';
    var gridTitle = '角色管理';
    var findall = "appRole_all.do";
    var addMsg = 'appRole_add.do';
    var deleteMsg = 'appRole_delete.do';
    var modifyMsg = 'appRole_modify.do';
    
    var renderTo = 'approle_grid';
    var seqValue = "app_role_seq"; //序列号名称
    var identityName = "roleId"; //主键名称
    var pageSize = 18;
    var gridHeight = 500;
    
    var sm = new Ext.grid.CheckboxSelectionModel();
    var cm = new Ext.grid.ColumnModel([sm, {
        header: "编号",
        width: 100,
        dataIndex: 'roleId'
    }, {
        header: "角色名称",
        width: 100,
        sortable: true,
        dataIndex: 'roleName',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "角色说明",
        width: 100,
        dataIndex: 'roleDesc',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "状态",
        width: 100,
        dataIndex: 'status',
        editor: {
            xtype: 'textfield'
        }
    }, {
        header: "权限",
        width: 100,
        dataIndex: 'rights',
        editor: {
            xtype: 'textfield'
        }
    }]);
    var Dict = Ext.data.Record.create([{
        name: 'roleId',
        type: 'int'
    }, {
        name: 'roleName',
        type: 'string'
    }, {
        name: 'roleDesc',
        type: 'string'
    }, {
        name: 'status',
        type: 'string'
    }, {
        name: 'rights',
        type: 'int'
    }]);
    
    var reader = new Ext.data.JsonReader({
        root: 'rows', //rows : 为服务器端传送过来的记录数值对象
        totalProperty: 'total' //results 为服务器端json传送过来的记录的行数, count(*)运算
    }, ['roleId', 'roleName', 'roleDesc', 'status', 'rights']);
    var saveHandler = function(e){
        var conn = new Ext.data.Connection();
        conn.request({
            url: modifyMsg,
            params: {
                'appRole.roleId': e.record.get("roleId"),
                'appRole.roleName': e.record.get("roleName"),
                'appRole.roleDesc': e.record.get("roleDesc"),
                'appRole.status': e.record.get("status"),
                'appRole.rights': e.record.get("rights")
            },
            success: function(resp, opt){
            },
            failure: function(resp, opt){
            }
        });
    }
    //add handle to deal with add action
    var addHandler = function(e){
        var conn = new Ext.data.Connection();
        conn.request({
            url: addMsg,
            params: {
                seqName: seqValue
            },
            success: function(resp, opt){
                var newId = Ext.util.JSON.decode(resp.responseText).newId;
                grid.getStore().insert(0, new Dict({
                    roleId: newId,
                    roleName: '',
                    roleDesc: '',
                    status: '',
                    rights: ''
                }));
                grid.startEditing(0, 0);
            },
            failure: function(resp, opt){
                Ext.Msg.alert('错误', '添加失败！');
            }
        })
    };
    
	var saveFunsHandler = function(ids, roleId,win) {
		var conn = new Ext.data.Connection();
        conn.request({
            url: 'appRole_assignFun.do',
            params: {
                ids: ids,
				roleId: roleId
            },
            success: function(resp, opt){
				win.close();
            },
            failure: function(resp, opt){
                Ext.Msg.alert("错误","修改失败！");
            }
        });
	}
    //权限分配
    function assginFunHandler(){
        openAssignWin();
    }

    function openAssignWin(funListStr, roleOwnFunIdList){
        var s = grid.getSelectionModel().getSelected();
        if (!s) return false;
        var win;
        var tree = new Ext.tree.TreePanel({
            title: '权限列表',
            height: 420,
            width: 400,
            useArrows: true,
            autoScroll: true,
            animate: true,
            enableDD: false,
            containerScroll: true,
            rootVisible: false,
            frame: true,
            root: new Ext.tree.AsyncTreeNode({
                text: '功能列表'
            }),
            loader: new Ext.tree.TreeLoader({
                url: 'functionTree_funListForTree.do',
				baseParams: {
					roleId: s.get(identityName)
				}
            }),
            buttons: [{
                text: '确定',
                handler: function(){
                    var ids = '', selNodes = tree.getChecked();
                    Ext.each(selNodes, function(node){
                        if (ids.length > 0) {
                            ids += ',';
                        }
                        ids+= node.id;
                    });
                    saveFunsHandler(ids, s.get(identityName),win);
                }
            }]
        });
        tree.getRootNode().expand(true);
        
        if (!win) {
            win = new Ext.Window({
                title: '信息录入',
                width: 410,
                height: 450,
                x: 100,
                y: 50,
                closeAction: 'close',
                plain: true,
                modal: true,
                items: tree
            });
        }
        win.show();
    }
    
    //-------------------------下面无需改动-----------------------------------------------------------
    
    var store = new Ext.data.Store({
        url: findall,
        reader: reader
    });
    store.load({
        params: {
            start: 0,
            limit: pageSize
        }
    });
    
    var editor = new Ext.ux.grid.RowEditor({
        saveText: '保存',
        cancelText: '取消',
        listeners: {
            afteredit: function(e){
                saveHandler(e);
            }
        }
    });
    
    var grid = new Ext.grid.GridPanel({
        renderTo: renderTo,
        frame: true,
        title: gridTitle,
        autoScroll: true,
        width: "auto",
        height: gridHeight,
        store: store,
        plugins: [editor],
        sm: sm,
        cm: cm,
        tbar: [{
            text: ' 增加 ',
            handler: function(e){
                addHandler(e)
            } //deal add
        }, {
            ref: '../removeBtn',
            text: ' 删除 ',
            disabled: true,
            handler: function(e){
                delHandler(e)
            } //处理删除函数 
        }, {
            ref: '../funAssignBtn',
            text: ' 权限分配 ',
            disabled: true,
            handler: function(){
                assginFunHandler();
            }
        }],
        viewConfig: {
            columnsText: "显示/隐藏列",
            sortAscText: "正序排列",
            sortDescText: "倒序排列"
        },
        bbar: new Ext.PagingToolbar({
            pageSize: pageSize,
            store: store,
            displayInfo: true,
            afterPageText: ' 共 {0} 页',
            beforePageText: '页 ',
            firstText: '第一页 ',
            prevText: '前一页',
            nextText: '下一页',
            lastText: '最后一页',
            refreshText: '刷新',
            displayMsg: '显示第 {0} 条到 {1} 条记录，一共 {2} 条',
            emptyMsg: "没有记录"
        })
    
    });
    
    grid.getSelectionModel().on('selectionchange', function(sm){
        grid.removeBtn.setDisabled(sm.getCount() < 1);
        grid.funAssignBtn.setDisabled(sm.getCount() != 1);
    });
    
    //删除的处理函数
    var delHandler = function(e){
        editor.stopEditing();
        var s = grid.getSelectionModel().getSelections();
        if (!s) 
            return false;
        Ext.Msg.show({
            title: '删除',
            buttons: Ext.MessageBox.YESNOCANCEL,
            msg: '确认删除？',
            fn: function(btn){
        		if(btn == "no" || btn == "cancel") return;
                var ids = "";
                for (var i = 0; i < s.length; i++) { //要删除的记录ID拼串
                    ids = ids + s[i].get(identityName) + ",";
                }
                var conn = new Ext.data.Connection();
                conn.request({
                    url: deleteMsg,
                    params: {
                        delIds: ids
                    },
                    success: function(resp, opt){
                        for (var i = 0; i < s.length; i++) { //把store中相应的记录删掉
                            grid.getStore().remove(s[i]);
                        }
                        store.reload();
                    },
                    failure: function(resp, opt){
                        Ext.Msg.alert('错误', '删除记录失败！');
                    }
                });
            }
        });
    }
});
